requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        jquery: 'jquery.min',
        jquery_route: 'jquery.route',
        bootstrap: "../../bootstrap-3.3.5/dist/js/bootstrap.min",
        menu : "../modules/index/menu",
        config: "../common/config",
        common:'../common/common',
        arttemplateUtil: '../js/common/arttemplate-util',
        ztree:'../plugins/ztree/js/jquery.ztree.core',
        ztreeCheck:'../plugins/ztree/js/jquery.ztree.excheck.min',
        ztreeHide:'../plugins/ztree/js/jquery.ztree.exhide',
        layer: '../plugins/layer/layer'
    },
    waitSeconds : 15,
	map : {
		'*' : {
			'css' : 'css'
		}
	},
    shim: { //引入没有使用requirejs模块写法的类库。backbone依赖underscore
    	'jquery': {
            exports: '$'
        },
        'bootstrap':['jquery'],
        'ztreeCheck':['css!../plugins/ztree/css/zTreeStyle/zTreeStyle.css'],
        'ztreeHide':['ztree']
    }
});
requirejs(['jquery', 'jquery_route','config', 'arttemplateUtil','menu','common','layer','ztree','ztreeCheck','ztreeHide'], 
		function($, jquery_route, config, arttemplateUtil,menu, common,layer,ztree,ztreeCheck,ztreeHide) {
	
	var loadTree = function(param){
		common.common_ajax_request('/api/v1/area_tree',param,false,function(data,code,msg){
			//console.debug(JSON.stringify(data));
			ztree_data = data;
			var setting = {check: {enable: true},data: {simpleData: {enable: true}},view: { showIcon: true, selectedMulti: true, nameIsHTML: true, fontCss: setFontCss_ztree }};
			area_tree=$.fn.zTree.init($("#ztreeShow"), setting, data);
			layer.closeAll('loading');
		}, null, "post");
	};
	var area_tree,ztree_data;
	$(document).ready(function(){
		common.loading();
		var st_id = $("#st_id").val()+"";//771620657657028608
		if(st_id != ''){
			$("#btitle").html("编辑小区配置模板");
			var param = {st_id:st_id};
			common.common_ajax_request('/api/v1/get_tran_area',param,false,function(data,code,msg){
				$("#templeteName").val(data.trans_name);
				loadTree({ids:data.tree_ids?data.tree_ids:""});
			});
		}else{
			loadTree({});
		}
	});
	
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchCondition     搜索条件
     * @param flag                  需要高亮显示的节点标识
     */
    function searchByFlag_ztree(treeId, searchCondition){
        //<2>.得到模糊匹配搜索条件的节点数组集合
        var highlightNodes = new Array();
        if (searchCondition != "") {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
        }
        //<3>.高亮显示并展示【指定节点s】
        highlightAndExpand_ztree(treeId, highlightNodes);
    }
     
    /**
     * 高亮显示并展示【指定节点s】
     * @param treeId
     * @param highlightNodes 需要高亮显示的节点数组
     */
    function highlightAndExpand_ztree(treeId, highlightNodes){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
        //<2>.收起树, 只展开根节点下的一级节点
        //close_ztree(treeId);
        //<3>.把指定节点的样式更新为高亮显示，并展开
        //alert(highlightNodes.length);
        if (highlightNodes != null) {
            for (var i = 0; i < highlightNodes.length; i++) {
            	searchResultIds.push(highlightNodes[i].tId);
                {
                    //高亮显示节点，并展开
                    highlightNodes[i].highlight = true;
                    treeObj.updateNode(highlightNodes[i]);
                    //高亮显示节点的父节点的父节点....直到根节点，并展示
                    var parentNode = highlightNodes[i].getParentNode();
                    var parentNodes = getParentNodes_ztree(parentNode);
                    treeObj.expandNode(parentNodes, true, false, true);
                    treeObj.expandNode(parentNode, true, false, true);
                }
            }
            //过滤不在搜索条件里面的节点
            var nodes = treeObj.transformToArray(treeObj.getNodes());
            var nodeLength = nodes.length;
            for (var i = 0; i < nodeLength; i++) {
            	if(!nodes[i].checked && !nodes[i].isParent){
            		if(searchResultIds.indexOf(nodes[i].tId)==-1){
            			treeObj.hideNode(nodes[i]);
            		}
            	}
            }
        }
    }
     
    /**
     * 递归得到指定节点的父节点的父节点....直到根节点
     */
    function getParentNodes_ztree(node){
        if (node != null) {
            var parentNode = node.getParentNode();
            return getParentNodes_ztree(parentNode);
        } else {
            return node;
        }
    }
     
    /**
     * 设置树节点字体样式
     */
    function setFontCss_ztree(treeId, treeNode) {
        if (treeNode.id == 0) {
            //根节点
            return {color:"#333", "font-weight":"bold"};
        } else if (treeNode.isParent == false){
            //叶子节点
            return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
        } else {
            //父节点
            return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
        }
    }
    
    function initTreeNodes(){
    	var treeObj = $.fn.zTree.getZTreeObj('ztreeShow');
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
        	if(treeNodes[i].isHidden){
        		treeObj.showNode(treeNodes[i]);
        	}
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
    }
	$("#ret_btn").click(function(){
		window.location.href="#logistics/deliveryset";
	});
	
	
	var searchResultIds = [];
	var curr_node_index = 0;
	var cur_offset_top = 0;
	$("#search_node_btn").click(function(){
		common.loading();
		window.setTimeout(function(){
			curr_node_index = 0;
			searchResultIds=[];
			cur_offset_top = 0;
			
			initTreeNodes();
			var searchText = $("#search_node_text").val();
	    	if(searchText == ''){
	    		//layer.msg("查询条件不能为空");
	    	}else{
	    		searchByFlag_ztree('ztreeShow', searchText);
	    		$("#searbox").scrollTop(0);
	    		if(searchResultIds.length > 0){
	    			cur_offset_top = $("#"+searchResultIds[curr_node_index]+"_a").offset().top - $("#searbox").offset().top;
	    			$("#searbox").animate({scrollTop:cur_offset_top},1000);//1000是ms,也可以用slow代替
	    		}else{
	    			layer.msg("没有查询结果");
	    		}
	    	}
	    	layer.closeAll('loading');
		}, 10);
	});
	
	/*$("#pre_node_btn").click(function(){
		if(searchResultIds.length == 0){
			layer.msg("没有查询结果");
			return;
		}
		if(curr_node_index==0){
			layer.msg("没有了");
			return;
		}
		curr_node_index = curr_node_index-1;
		
		$("#searbox").scrollTop(0);
		cur_offset_top = $("#"+searchResultIds[curr_node_index]+"_a").offset().top - $("#searbox").offset().top;
		$("#searbox").scrollTop(cur_offset_top);
	});
	
	$("#next_node_btn").click(function(){
		if(searchResultIds.length == 0){
			layer.msg("没有查询结果");
			return;
		}
		if(curr_node_index+1 == searchResultIds.length){
			layer.msg("没有了");
			return;
		}
		curr_node_index = curr_node_index+1;
		
		$("#searbox").scrollTop(0);
		cur_offset_top = $("#"+searchResultIds[curr_node_index]+"_a").offset().top - $("#searbox").offset().top;
		$("#searbox").scrollTop(cur_offset_top);
	});*/
	
	$("#save_btn").click(function(){
		var checkedNodes = area_tree.getCheckedNodes(true);
		
		var templeteName = $("#templeteName");
		if(templeteName.val() == 0 || templeteName.val() == ''){
			layer.alert("小区配置模板名称不能为空");
			return;
		}
		
		if(checkedNodes.length<=0){
			layer.alert("至少选择一个社区");
			return;
		}
		
		jQuery(this).attr('disabled','disabled');
		
		var allArea = [];
		var ids=[],areaNames=[], parentIds = [], parentNames=[], pidNames=[];
		
    	for(var i=0;i<checkedNodes.length;i++){
    		var o={};
    		o.area_id=checkedNodes[i].id;
    		o.area_name=checkedNodes[i].name;
    		
    		if(checkedNodes[i].isParent){//如果不是子节点，则不记录id和name
    			parentIds.push(checkedNodes[i].id);
    			parentNames.push(checkedNodes[i].name);
    			o.is_community=false;
    			//continue;
    		}else{
    			ids.push(checkedNodes[i].id);
	    		areaNames.push(checkedNodes[i].name);
	    		pidNames.push(checkedNodes[i].pId+"@"+checkedNodes[i].name);
	    		o.is_community=true;
    		}
    		allArea.push(o);
    		//area_tree.setChkDisabled(checkedNodes[i],true,true,true);
    	}
    	var obj = {};
    	obj.community_ids = ids.join(",");
    	obj.community_names = areaNames.join(",");
    	obj.parent_ids = parentIds.join(",");
    	
    	obj.parent_names = parentNames.join(",");
    	obj.pid_names = pidNames.join(",");
    	
    	var allAreaStr = JSON.stringify(allArea);
    	var tran_area_infoStr = JSON.stringify(obj);
    	
    	
    	var param = {};
    	param.id = $("#st_id").val()+"";
    	param.trans_name = templeteName.val();
    	param.areaDetailStr = allAreaStr;
    	param.tranAreaInfoStr = tran_area_infoStr;
    	
    	
    	common.common_ajax_request('/api/v1/vip_trans_area_save',param,false,function(data,code,msg){
			if(code==200 && msg.businessCode==0){
        		window.layer.alert('保存成功!', {
      			  icon: 1,closeBtn:false
      			}, function(){
      				//刷新当前页面
      				window.location.href="#logistics/deliveryset";
      			}); 
			}else{
				layer.alert(msg.businessNote);
			}
		}, "", "post"); 
	});
});